﻿using Exceptionless;
using Exceptionless.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Brc_DSB.ServiceForward.ExceptionFilter
{
    public class ExceptionAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            var hasHandle = filterContext.ExceptionHandled;
            string message = string.Format("时间：{0}消息内容：{1}堆栈：{2}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + System.Environment.NewLine, filterContext.Exception.Message + System.Environment.NewLine, filterContext.Exception.StackTrace + System.Environment.NewLine);
            ExceptionlessClient.Default.CreateLog(message, LogLevel.Error).Submit();
            if (!hasHandle)
            {
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
                    filterContext.Result = new ErrorResult(false, "服务器错误");
                }
                else
                {
                    var url = filterContext.RequestContext.HttpContext.Request.Path;
                    if (filterContext.Exception.Message.Contains("Unable to Connect"))
                    {
                        filterContext.Result = new RedirectResult(url);
                    }
                    else
                    {
                        filterContext.Result = new RedirectResult("~/Error");
                    }
                }
            }
            filterContext.ExceptionHandled = true;
        }
    }
}